package com.jack;

import com.jack.concurrentdb.UserInfo;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.util.List;

public class Main {

    //i don't known what's going to do //
    static int INSERT_NUM =  90 * 10000;

    static long start = 0;

    public static void main(String[] args) throws Exception {
        String config = "mybatis-config.xml";

        InputStream inputStream = Resources.getResourceAsStream(config);

        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {

            Long count = sqlSession.selectOne("com.jack.concurrentdb.UserMapper.selectCount");
            System.out.println("数据总数："+ count);

            //测试查询数据
//            queryBatch(sqlSession);

//            插入测试数据
            insertBatch(sqlSession, count);

        } finally {
            sqlSession.close();

        }
    }


    //测试查询数据
    private static void queryBatch(SqlSession sqlSession){

        int force = INSERT_NUM;
        while (true) {
            int i = INSERT_NUM / force;
            System.out.println("查询比 " + i + " 大的数据");

            start = System.currentTimeMillis();
            List<UserInfo> userInfo = sqlSession.selectList("com.jack.concurrentdb.UserMapper.selectAgeGt", i);
            System.out.println("没有索引字段比较 --总耗时：" + ((System.currentTimeMillis() - start)));

            start = System.currentTimeMillis();
            List<UserInfo> userInfo2 = sqlSession.selectList("com.jack.concurrentdb.UserMapper.selectGt", i);
            System.out.println("有索引字段比较 --总耗时：" + ((System.currentTimeMillis() - start)));

            System.out.println("-------------------");

            force = force / 10;
            if (force == 1 / 10) break;
        }
    }

    //插入测试数据
    private static void insertBatch(SqlSession sqlSession, long lastKeyId) {
        int count = 0;
        Integer lastKey = Math.toIntExact(lastKeyId);
        while (true){
            count++;
            int id = lastKey + count;

            UserInfo info = new UserInfo();
            info.setAge(id);
            info.setEvaluate("大大");
            info.setFraction( id % 2);
            info.setName("Clone " + id);
            info.setSkill("学习 " + id);
            sqlSession.insert("com.jack.concurrentdb.UserMapper.insert", info);
            sqlSession.commit();
            info = null;
            System.out.println(count);
            if(count == INSERT_NUM) break;
        }
    }
}
